import express from 'express';
import base64 from 'base-64';
import axios from "axios";
import dayjs from "dayjs";
import {getDB, isBlzTokenExpired} from "../utils/Utils.js";

const router = express.Router();


router.get('/token', async function (req, res, next) {
    const db = (await getDB())
    // 检查token是否过期
    if (db.data.blzHsToken === null || db.data.blzHsToken === '' || isBlzTokenExpired(db.data.expiresIn)) {
        // 获取token
        const credentials = `${process.env.BATTLENET_HS_CLIENT_ID}:${process.env.BATTLENET_CLIENT_SECRET}`;
        const basicAuth = `Basic ${base64.encode(credentials)}`
        const reqConfig = {
            method: 'POST', url: `${process.env.BATTLENET_HS_BASIC_OAUTH_URL}`, headers: {
                Authorization: `Bearer ${basicAuth}`, 'Content-Type': 'application/x-www-form-urlencoded',
            }, auth: {
                username: process.env.BATTLENET_HS_CLIENT_ID, password: process.env.BATTLENET_HS_SECRET,
            }, data: {
                'grant_type': 'client_credentials',
            }
        }
        const ret = await axios(reqConfig)
        if (ret.status === 200) {
            db.data.blzHsToken = ret.data.access_token
            db.data.expiresIn = dayjs().add(ret.data.expires_in, 's').format('YYYY-MM-DD HH:mm:ss')
            await db.write()
            ret.data.expired = true
            ret.data.expires_in = db.data.expiresIn
            res.json(ret.data)
        } else {
            res.json({error: 'error'})
        }
    } else {
        console.log(db.data)
        res.json({access_token: db.data.blzHsToken, expires_in: db.data.expiresIn, expired: false})
    }
});


router.get('/test', async function (req, res, next) {
    return res.json({success: true})
})


export default router
